<?php

namespace app\api\controller\user;

use app\api\controller\Controller;
use app\api\model\order\Order as OrderModel;
use app\api\model\product\Category;
use app\api\model\settings\Setting as SettingModel;
use app\api\service\pay\PayService;
use app\common\enum\order\OrderPayTypeEnum;
use app\common\service\qrcode\ExtractService;
use app\common\model\supplier\Service as ServiceModel;
use app\common\model\supplier\User as SupplierUserModel;
use app\common\model\app\App as AppModel;
use app\common\enum\order\OrderTypeEnum;
use think\Exception;
use think\facade\Request;
use think\facade\Db;

/**
 * 我的订单
 */
class Order extends Controller
{
    // user
    private $user;

    /**
     * 构造方法
     */
    public function initialize()
    {
		
		 // $yufukuan =SettingModel::getItem('store')['yufukuan'];
		 // dump($yufukuan);
		 // exit;
		
        parent::initialize();
        $this->user = $this->getUser();   // 用户信息

    }
    public function track($order_id){

        $list = Db::name('rengongguiji')
            ->where('dingdn_id', $this->postData()['order_id'])
            ->whereIn('status', [1, 2])
            ->field('guijiForm,create_time')
            ->order('create_time desc')
            ->select();
        return $this->renderSuccess('', compact('list'));

    }
	public function index_chuli(){ //新生成订单
	  $data = $this->postData();
	  //$daid= Db::name('jiedan_order')->where(['user_id'=>$this->user['user_id'],'status'=>0])->find();
		// if($daid){
			 
			//$data['time']= time();
		//	Db::name('jiedan_order')->where(['user_id'=>$this->user['user_id'],'status'=>0])->update($data); 
		//	$list = $daid['id'];
		// }else{
        if ($data['julidegoglishu'] < 28){
            return $this->renderError('距离过短不能下单');
        }


        $user = $this->getUser();
        if (empty($user['mobile'])){
            return $this->renderError('请先到【我的】页面,绑定手机号');
        }

        $isBlacklist = Db::name('blacklist_mobile')->where(['mobile'=>$user['mobile']])->find();
        if ($isBlacklist){
            return $this->renderError('系统维护中，暂无法下单');
        }
        // 同省价格计算
        // if (mb_substr($data['kaishidizhi'], 0, 2, 'UTF-8') === mb_substr($data['jishudizhi'], 0, 2, 'UTF-8')) {
        //     $category = (new Category())->where(['category_id' =>  $data['fenleifen_index']])->find();
        //     $total_price =  bcadd($category['jiage'], bcmul($data['julidegoglishu'], $category['eweijiage'], 2), 2);
        //     // 保存计算后的总价到 fenleifen_jiage 字段，保留原来的分类 id
        //     $data['fenleifen_jiage'] = $total_price;
        // }
		$data['time']= time();
		$data['user_id']= $this->user['user_id'];
		$list = Db::name('jiedan_order')->insertGetId($data);
		// }
	return $this->renderSuccess('', compact('list'));	 
	 }
	 public function pay_chuli(){
		 $list= Db::name('jiedan_order')->where(['user_id'=>$this->user['user_id'],'status'=>0,'id'=>$this->postData()['order_id']])->find();
		  if ($this->user['user_id'] == 10935){
             $list['fenleifen_jiage'] = "1.00";
             $list['fenleifen_jiage_jisuan'] = "1";
         }
//
		  $countde = Db::name('order')->where(['user_id'=>$this->user['user_id'],'order_status'=>10,'pay_status'=>10])->count();
		 
		 if($countde>3  && $this->getUser(false)['user_id'] == '10441'  && $this->getUser(false)['user_id'] == '10448'){
			 $list =0;
			      return $this->renderSuccess('', compact('list'));
		 }
		
	
		$fenleifen = Db::name('category')->where(["category_id"=>$list['fenleifen']])->find();
		$data['order_no']= date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
		$data['total_price']= $list['fenleifen_jiage']; 
		$data['pay_price']= $list['fenleifen_jiage']; 
		$data['pay_type']= 20;
		$data['pay_status']= 10; 
		$data['delivery_type']= 30; 
		$data['extract_store_id']= 1; 
		$data['delivery_status']= 10; 
		$data['order_source']= 10;  
		$data['user_id']= $list['user_id'];  
		$data['shop_supplier_id']= 0; 
		$data['ding_id']= $list['id'];   //zhed  
		$data['create_time']=time();  
		$data['app_id']=10001;
		
		$orderlist= Db::name('order')->where(['user_id'=>$this->user['user_id'],'ding_id'=>$list['id'],"pay_status"=>10])->find();
if(!empty($orderlist)){
	
	
		Db::name('order')->where(['ding_id'=>$list['id'],'user_id'=>$list['user_id'],"pay_status"=>10])->update([
		'order_no11'=> date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8),
		'total_price'=>$list['fenleifen_jiage'],
		'pay_price'=>$list['fenleifen_jiage'],
		'create_time'=>time()
		]);
		$ordiridde = $orderlist['order_id'];
}else{
	$ordiridde = Db::name('order')->insertGetId($data);
	
}
 $yufukuan= $vars['values'] = SettingModel::getItem('store')['yufeiyufu'];

// dump($yufukuan);
// exit;
 $baoxianbi =SettingModel::getItem('store')['baoxianbi'];
 
 
 

		return $this->renderSuccess('', compact('list','fenleifen','ordiridde','yufukuan','baoxianbi')); 
	 }
    /**
     * 我的订单列表  ding_id
     */
    public function lists($dataType)
    {
        $data = $this->postData();
        $model = new OrderModel;
        $list = $model->getList($this->user['user_id'], $dataType, $data);
        $show_alipay = PayService::isAlipayOpen($data['pay_source'], $this->user['app_id']);
        $app = AppModel::detail();
        $mch_id = $app['mchid'];
        return $this->renderSuccess('', compact('list', 'show_alipay', 'mch_id'));
    }

    /**
     * 订单详情信息
     */
    public function detail($order_id, $pay_source = '')
    {
		
		
        // 订单详情
        $model = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
	
        // 剩余支付时间
        if ($model['pay_status']['value'] == 10 && $model['order_status']['value'] != 20 && $model['pay_end_time'] != 0) {
            $model['pay_end_time'] = $this->formatPayEndTime($model['pay_end_time'] - time());
        } else {
            $model['pay_end_time'] = '';
        }
		
        // 该订单是否允许申请售后
        $model['isAllowRefund'] = $model->isAllowRefund();
		
		
        // $model['supplier']['supplier_user_id'] = (new SupplierUserModel())->where('shop_supplier_id', '=', $model['shop_supplier_id'])->value('supplier_user_id');
		
	
        $app = AppModel::detail();
        $mch_id = $app['mchid'];
		
			
        return $this->renderSuccess('', [
            'order' => $model,  // 订单详情
            'setting' => [
                // 积分名称
                'points_name' => SettingModel::getPointsName(),
                //是否开启客服
                'service_open' => SettingModel::getSysConfig()['service_open'],
                //店铺客服信息
                'mp_service' => ServiceModel::detail($model['shop_supplier_id']),
            ],
            'show_alipay' => PayService::isAlipayOpen($pay_source, $model['app_id']),
            'mch_id' => $mch_id
        ]);
    }

    /**
     * 支付成功详情信息
     */
    public function paySuccess($order_id)
    {
        $order_arr = explode(',', $order_id);
        $order = [
            'pay_price' => 0,
            'points_bonus' => 0
        ];
        $orderRow = null;
        foreach ($order_arr as $id) {
            $orderRow = OrderModel::getUserOrderDetail($id, $this->user['user_id']);
            $order['pay_price'] += $orderRow['pay_price'];
            $order['points_bonus'] += $orderRow['points_bonus'];
        }

        $order_address = Db::name('jiedan_order')->where('id', $orderRow['ding_id'])->find();

        $order['pay_price'] = round($order['pay_price'], 2);

        $em = '2765145152@qq.com';
    //    $em = '854013212@qq.com';
        // 处理包装方式显示
        $packageTypes = [
            0 => '',
            1 => '缠膜包装',
            2 => '电动木架',
            3 => '摩托木架',
            4 => '木箱铁架',
        ];
        $package_type = $packageTypes[$orderRow['package_method']] ?? '';

        // 处理配送方式显示
        // $deliveryTypes = [
        //     10 => '快递',
        //     20 => '自提',
        //     30 => '',
        // ];
        $delivery_type = $orderRow['delivery_type']['text'];
        $user = $this->getUser();
        $detail = [
            'order_no' => $orderRow['order_no'],
            "start_city"=> $order_address['kaishidizhi'],
            "end_city"=> $order_address['jishudizhi'],
            "sender"=> $orderRow['shuju_fahuoren'],
            "sender_phone"=> $orderRow['shuju_fahuodianhua'],
            "receiver"=>$orderRow['shuju_shouhuren'],
            "receiver_phone"=> $orderRow['shuju_shouhurendianhua'],
            "quoted_price"=> $orderRow['baojiaMoney'],
            "insurance_fee"=> $orderRow['baojiaMoneys'],
            "pickup_time"=> $orderRow['shangmen_time'],
            "package_type"=> $package_type,
            "delivery_type"=> $delivery_type,
            "total_price" => $orderRow['total_price'],
            "pay_price" =>  $orderRow['pay_price'],
            "goods_type" => $orderRow['fenleimingc'], // 货物类别
            "user_phone" => $user['mobile'],
        ];
        // 发送通知邮件
        // 计算项目根目录（app/api/controller/user → ../../../../）
        $rootPath = dirname(__DIR__, 4) . DIRECTORY_SEPARATOR;
        $cmd = "python3 " . $rootPath . "em.py " . $em . " " . escapeshellarg(json_encode($detail, JSON_UNESCAPED_UNICODE));
        $setCharset = 'export LANG=en_US.UTF-8;';
        $execRes =shell_exec($setCharset . $cmd);
        $user = $this->getUser();

        $click_id = $this->request->param('click_id','');
        $res = (new \TengxunAD())->add($user['open_id'],'付费',$click_id,$orderRow['pay_price']);

       
        return $this->renderSuccess('', compact('order'));
    }

    /**
     * 获取物流信息
     */
    public function express($order_id)
    {
        // 订单信息
        $order = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        if (!$order['express_no']) {
            return $this->renderError('没有物流信息');
        }
        // 获取物流信息
        $model = $order['express'];
        $express = $model->dynamic($model['express_name'], $model['express_code'], $order['express_no']);
        if ($express === false) {
            return $this->renderError($model->getError());
        }
        return $this->renderSuccess('', compact('express'));
    }

    /**
     * 取消订单
     */
    public function cancel($order_id)
    {
	
        $model = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
			
	
        if ($model->cancel($this->user)) {
            return $this->renderSuccess('订单取消成功');
        }
        return $this->renderError($model->getError() ?: '订单取消失败');
    }

    /**
     * 确认收货
     */
    public function receipt($order_id)
    {
        $model = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        if ($model->receipt()) {
            return $this->renderSuccess('收货成功');
        }
        return $this->renderError($model->getError() ?: '收货失败');
    }
 public function pay_xiugai_shuliang()
    {
		
		
        $params = $this->postData();
        //var_dump($params['order_id']);
        if($params['order_id']&&$params['jiage']){
        	Db::name('order')->where(['order_id'=>$params['order_id']])->update(['total_price'=>$params['jiage'],'pay_price'=>$params['jiage']]);
        }
    }
    /**
     * 立即支付
     */
    public function pay()
    {
		
		
        $params = $this->postData();
		// $datasavder['shuju_fahuoren'] =  $params['shuju_fahuoren'];
		// $datasavder['shuju_fahuodianhua'] =  $params['shuju_fahuodianhua'];
		// $datasavder['shuju_shouhuren'] =  $params['shuju_shouhuren'];
		// $datasavder['shuju_shouhurendianhua'] =  $params['shuju_shouhurendianhua'];
		// $datasavder['taishu'] =  $params['taishu'];
		// $datasavder['radioValue'] =  $params['radioValue'];   
		
			// $dasddadd= Db::name('order')->where(['order_id'=>$this->postData()['order_id'],'user_id'=>$this->user['user_id']])->find();
			// Db::name('order')->where(['order_id'=>$this->postData()['order_id'],'user_id'=>$this->user['user_id']])->value('ding_id');
			$dasddadd=Db::name('jiedan_order')->where(['id'=>Db::name('order')->where(['order_id'=>$this->postData()['order_id'],'user_id'=>$this->user['user_id']])->value('ding_id')])->field('fenleifen,fenleifen_index')->find();
			//一级  
			
			$fenleiming = Db::name('category')->where(['category_id'=>$dasddadd['fenleifen']])->value('name') .'_'. Db::name('category')->where(['category_id'=>$dasddadd['fenleifen_index']])->value('name');
			
		// 判断用户绑定手机没，绑定的手机号不能再黑名单中
        $user = $this->getUser();
        if (empty($user['mobile'])){
            return $this->renderError('请先到【我的】页面,绑定手机号');
        }

        $isBlacklist = Db::name('blacklist_mobile')->where(['mobile'=>$user['mobile']])->find();
        if ($isBlacklist){
            return $this->renderError('系统维护中，暂无法下单');
        }
        $orderRow = Db::name('order')->where(['order_id'=>$this->postData()['order_id']])->find();

        // 省外 && 送货 +88运费
        if (isset($params['delivery_type']) && $params['delivery_type'] == 10){
            $order_address = Db::name('jiedan_order')->where('id', $orderRow['ding_id'])->find();
            if (mb_substr($order_address['kaishidizhi'], 0, 3, 'UTF-8') != mb_substr($order_address['jishudizhi'], 0, 3, 'UTF-8')){
                Db::name('order')->where(['order_id'=>$this->postData()['order_id']])->save([
                    'total_price'=> $orderRow['total_price'] + 88,
                    'pay_price' =>  $orderRow['pay_price'] + 88,
                ]);
            }
        }
			Db::name('order')->where(['order_id'=>$this->postData()['order_id'],'user_id'=>$this->user['user_id']])->save([
			'shuju_fahuoren'=>$params['shuju_fahuoren'],
			'shuju_fahuodianhua'=>$params['shuju_fahuodianhua'],
			'shuju_shouhuren'=>$params['shuju_shouhuren'],
			'shuju_shouhurendianhua'=>$params['shuju_shouhurendianhua'],
			'quhuoshijian'=>$params['quhuoshijian']?$params['quhuoshijian']:'1',
			'taishu'=>$params['taishu'],
			'shangmen_time'=>$params['shangmen_time'],
			'shuju_beizhu'=>$params['shuju_beizhu'],
			'radioValue'=>$params['radioValue'],
			'fenleimingc'=>$fenleiming,
			'isBaojia'=>$params['isBaojia']== "true"?1:0,
			'isyufu'=>$params['isyufu']== "true"?1:0,
			'isyufumoney'=>$params['isyufu']== "true"?SettingModel::getItem('store')['yufeiyufu']:0,
			'baojiaMoney'=>$params['baojiaMoney'],
			'baojiaMoneys'=>$params['baojiaMoneys'],
            'package_method'=> $params['package_method'] ?? 0,
            'delivery_type' => $params['delivery_type'] ?? 30,
			]);
		
        $payDetail = OrderModel::orderInfo($params['order_id'], $this->user);
        if ($this->request->isGet()) {
            // 开启的支付类型
            $payTypes = AppModel::getPayType($payDetail['app_id'], $params['pay_source']);
            // 支付金额
            $payPrice = $payDetail['pay_price'];
            $balance = $this->user['balance'];
            return $this->renderSuccess('', compact('payTypes', 'payPrice', 'balance'));
        }
        // 订单支付事件
        $model = new OrderModel;
        if (!$model->onPay($params, $this->user)) {
            return $this->renderError($model->getError() ?: '订单支付失败');
        }
        // 构建支付请求
        $payInfo = $model->OrderPay($this->getUser(), $params);
        if (!$payInfo) {
            return $this->renderError($model->getError() ?: '订单支付失败');
        }

        $click_id = isset($params['click_id']) ? $params['click_id'] : '';
        $res = (new \TengxunAD())->add($user['open_id'],'下单',$click_id,$orderRow['pay_price']);

		
		Db::name('jiedan_order')->where(['user_id'=>$this->user['user_id'],'status'=>0])->update(['status'=>1]);
        // 支付状态提醒
        return $this->renderSuccess('', [
            'order_id' => $payInfo['order_id'],   // 订单id
            'pay_type' => $payInfo['payType'],  // 支付方式
            'payment' => $payInfo['payment'],   // 微信支付参数
            'order_type' => OrderTypeEnum::MASTER, //订单类型
            'use_balance' => $payInfo['use_balance'],// 是否使用余额
            'return_Url' => $params['pay_source'] == 'h5' ? urlencode(base_url() . "h5/pages/order/myorder") : '', //h5支付跳转地址
        ]);
    }

    /**
     * 获取订单核销二维码
     */
    public function qrcode($order_id, $source)
    {
        // 订单详情
        $order = OrderModel::getUserOrderDetail($order_id, $this->user['user_id']);
        // 判断是否为待核销订单
        if (!$order->checkExtractOrder($order)) {
            return $this->renderError($order->getError());
        }
        $Qrcode = new ExtractService(
            $this->app_id,
            $this->user,
            $order_id,
            $source,
            $order['order_no']
        );
        return $this->renderSuccess('', [
            'qrcode' => $Qrcode->getImage(),
        ]);
    }

    private function formatPayEndTime($leftTime)
    {
        if ($leftTime <= 0) {
            return '';
        }

        $str = '';
        $day = floor($leftTime / 86400);
        $hour = floor(($leftTime - $day * 86400) / 3600);
        $min = floor((($leftTime - $day * 86400) - $hour * 3600) / 60);

        if ($day > 0) $str .= $day . '天';
        if ($hour > 0) $str .= $hour . '小时';
        if ($min > 0) $str .= $min . '分钟';
        return $str;
    }

    /**
     * 计算订单价格
     */
    public function calculationOrderPrice(){
        $params = $this->request->param();
        $categoryID = $params['category_id'];
        $startAddressName = $params['start_address_name'];
        $endAddressName = $params['end_address_name'];
        $startLat = $params['start_lat'];
        $startLng = $params['start_lng'];
        $endLat = $params['end_lat'];
        $endLng = $params['end_lng'];
        $distance = calculate_distance($startLat,$startLng,$endLat,$endLng);
        if ($distance < 28) {
            return $this->renderError('距离过短不能下单');
        }
        $price = $this->calculationPrice($categoryID,$startAddressName,$endAddressName,$distance);
        return $this->renderSuccess('', ['price'=>$price,'distance'=>$distance]);
    }

    /**
     * 计算订单价格
     * @param string $startAddressName 出发地名称
     * @param string $endAddressName 目的地名称
     * @param float $distance 距离（公里）
     * @return float 订单价格
     */
    private function calculationPrice($categoryID,$startAddressName,$endAddressName,$distance)
    {
        // 判断是否同省 通过地址名称前两个字短判断是否同省
        $startProvince = substr($startAddressName,0,2);
        $endProvince = substr($endAddressName,0,2);
        $cateRow = Db::name('category')->where(['category_id'=>$categoryID])->find();
        if ($startProvince == $endProvince) {
            // 同省，起步价
            $price = $cateRow['jiage'];
            // 每公里价格
            $unitPrice = $cateRow['eweijiage'];
        } else {
            // 不同省，按省外价格计算
            // 判断是否是热门城市
            $isHotRoute = $this->checkHotRoute($startAddressName, $endAddressName, $startProvince, $endProvince);
            
            if ($isHotRoute) {
                $price = $cateRow['jiage2'];
                // 每公里价格
                $unitPrice = $cateRow['eweijiage2'];
            } else {
                $price = $cateRow['jiage1'];
                // 每公里价格
                $unitPrice = $cateRow['eweijiage1'];
            }    
        }

        $total = bcadd($price,bcmul($distance, $unitPrice, 2),2);

        return $total;
    }

    /**
     * 检查是否为热门路线
     * @param string $startAddressName 起始地址名称
     * @param string $endAddressName 目的地址名称
     * @param string $startProvince 起始省份
     * @param string $endProvince 目的省份
     * @return bool 是否为热门路线
     */
    private function checkHotRoute($startAddressName, $endAddressName, $startProvince, $endProvince)
    {
        try {
            // 查询两个省份的所有热门地区
            $hotDistricts = Db::name('remeng_list')
                ->where('province', 'in', [$startProvince, $endProvince])
                ->field('district')
                ->select()
                ->toArray();

            if (empty($hotDistricts)) {
                return false;
            }

            // 检查起始地址是否包含热门地区
            $startIsHot = $this->addressContainsHotDistrict($startAddressName, $hotDistricts);
            // 检查目的地址是否包含热门地区
            $endIsHot = $this->addressContainsHotDistrict($endAddressName, $hotDistricts);

            // 只要起始地址或目的地址中任意一个包含热门地区，就判定为热门路线
            return $startIsHot || $endIsHot;

        } catch (\Exception $e) {
            // 异常情况下返回false，按普通路线处理
            return false;
        }
    }

    /**
     * 检查地址是否包含热门地区
     * @param string $address 地址名称
     * @param array $hotDistricts 热门地区列表
     * @return bool 是否包含热门地区
     */
    private function addressContainsHotDistrict($address, $hotDistricts)
    {
        if (empty($address) || empty($hotDistricts)) {
            return false;
        }

        foreach ($hotDistricts as $item) {
            $district = $item['district'] ?? '';
            if (!empty($district) && strpos($address, $district) !== false) {
                return true;
            }
        }

        return false;
    }
}